package com.computer.fundamentals.concurrentprogram;

/**
 * 这里以经典的线程安全问题——售票问题来演示如何使用Thread类，并利用synchronized来解决线程安全问题
 */
public class ThreadDemo {

    public static void main(String[] args) {
        System.out.println(Thread.currentThread().getName() + ": 现在开始售票！");
        Thread t1 = new MyThread();
        Thread t2 = new MyThread();
        Thread t3 = new MyThread();

        t1.start();
        t2.start();
        t3.start();
    }

}

class MyThread extends Thread {
    public static int tickets = 100;

    @Override
    public void run() {
        while (true) {
            synchronized (MyThread.class) { // 上类锁
                if (tickets > 0) {
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    tickets--;
                    System.out.println(Thread.currentThread().getName() + ": 售票1张" + ", 还剩余" + tickets + "张");
                }else {
                    break;
                }
            }
        }
    }
}